import os

import cv2
import numpy as np
import skimage
from matplotlib import pyplot as plt
from skimage import img_as_ubyte, img_as_bool
from skimage import morphology

def morphology(img):
    kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 14))  # 腐蚀矩阵
    iFushi = cv2.morphologyEx(img, cv2.MORPH_DILATE, kernel1)  # 对文字腐蚀运算
    cv2.imshow('fushi', iFushi)

    kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 40))  # 膨胀矩阵
    iPengzhang = cv2.morphologyEx(iFushi, cv2.MORPH_ERODE, kernel2)  # 对背景进行膨胀运算
    cv2.imshow('pengzhang', iPengzhang)

    # 背景图和二分图相减-->得到文字
    jian = np.abs(iPengzhang - img)
    cv2.imshow("jian", jian)

    kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 6))  # 膨胀
    iWenzi = cv2.morphologyEx(jian, cv2.MORPH_DILATE, kernel3)  # 对文字进行膨胀运算
    cv2.imshow('wenzi', iWenzi)







#img = img[:, :, ::-1]


#imgcut = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#thrpic = 255 - cv2.adaptiveThreshold(imgcut, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

            #                         cv2.THRESH_BINARY, 31, 11)

#median = cv2.medianBlur(thrpic, 5)
#输入是二值化后的图片
#thrpic = cv2.Canny(thrpic, 20, 250)


#img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#difference = (img_gray.max() - img_gray.min()) // 1.5
#mean = img_gray.mean()
#_, img_binary_1 = cv2.threshold(img_gray, difference, 1, cv2.THRESH_BINARY)
#_, img_binary_2 = cv2.threshold(img_gray, mean, 1, cv2.THRESH_BINARY)
#img_binary = cv2.adaptiveThreshold(img_gray, 1, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 0)

path = './img/up'
listimg = os.listdir(path)

for i in listimg:
    img = cv2.imread(os.path.join(path,i))

    Grayimg = 255 - cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    cv2.imshow("Grayimg", Grayimg)

    # 中值滤波器
    median = cv2.medianBlur(Grayimg, 5)

    cv2.imshow("median-image", median)
   # cv2.imwrite(os.path.join("./median-img",i), median)

    # 2、直方图均衡化：
    hist = cv2.equalizeHist(Grayimg)
    cv2.imshow('hist', hist)
    # 3、二值化处理：
    # 阈值为140
    th2 = cv2.adaptiveThreshold(Grayimg, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                     cv2.THRESH_BINARY, 5, 3)
    #thrpic = cv2.Canny(th2, 20, 250)
    median = cv2.blur(th2, (5,5))

    #ret, binary = cv2.threshold(hist, 210, 255, cv2.THRESH_BINARY)
    cv2.imshow("adaptiveThreshold-image", th2)
    cv2.imshow("canny",median)


    #cv2.imshow("img_as_ubyte-image", thrpic)
    # 二值形态处理
    # morphology(binary)

    cv2.waitKey()



#cv2.imshow("2",median)
#cv2.imshow("3",img_binary)
#cv2.waitKey()
